﻿using BaseUtils.AppConfig;
using SqlSugar;
using System;
using System.Collections.Generic;
using static DatabaseCore.DBCommon;

namespace DatabaseCore.Mysql
{
    public class MysqlHelper 
    {
        private SqlSugarClient db;

        //public MysqlHelper(DBConfig dBConfig)
        //{
        //    dBConfig.DbType = "MySql";
        //    db = GetOpenConnection(dBConfig);
        //}

        /// <summary>
        /// 查询所有数据
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <returns></returns>
        public List<T> QueryAll<T>() where T : class, new()
        {
            return db.Queryable<T>().ToList();
        }

        /// <summary>
        /// 根据条件查询数据
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="whereExpression"></param>
        /// <returns></returns>
        public List<T> Query<T>(System.Linq.Expressions.Expression<Func<T, bool>> whereExpression) where T : class, new()
        {
            return db.Queryable<T>().Where(whereExpression).ToList();
        }

    
        /// <summary>
        /// 更新数据
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="entity"></param>
        /// <returns></returns>
        public bool Update<T>(T entity) where T : class, new()
        {
            return db.Updateable(entity).IgnoreNullColumns().ExecuteCommand() > 0;
        }

        /// <summary>
        /// 删除数据
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="entity"></param>
        /// <returns></returns>
        public bool Delete<T>(T entity) where T : class, new()
        {
            return db.Deleteable(entity).ExecuteCommand() > 0;
        }


        public string Query(string pt, string stationName, string materialName)
        {

            string sql = "SELECT  upload_code  FROM  c_mes_recipe_datil_t " +
                "WHERE  RECIPE_ID IN( SELECT  ID  FROM   c_mes_recipe_t " +
                "WHERE  TOTAL_ID IN ( SELECT group_number FROM  c_mes_production_t " +
                "WHERE  PRODUCTION_TYPE ="+"\""+pt+ "\""+")" + " AND STATION_ID IN(  SELECT ID FROM  c_mes_station_t " +
                "WHERE  STATION_NAME ="+"\""+stationName + "\"" + ")) AND MATERIAL_NAME ="+ "\""+materialName + "\"";
            
           
               var value= db.Ado.SqlQuery<string>(sql) ;


               return value[0];
        }

        public T Install<T>(T t) where T : class, new()
        {
            return db.Insertable(t).ExecuteReturnEntity();
        }

        //int DataSourceClient.Update<T>(T t)
        //{
        //    throw new NotImplementedException();
        //}

        public MysqlHelper()
        {
        }
    }
}
